
import { type ClassValue, clsx } from "clsx";
import { cloneDeep } from "lodash-es";
import { twMerge } from "tailwind-merge";
import { NextResponse } from "next/server";

export const setJson = ({ code, message, data }: any = {}) => {
  return {
    code: code || 0,
    message: message || "ok",
    data: data || null,
  };
};
export function isJsonString(str: string) {
  try {
    let obj = JSON.parse(str);
    if (obj && typeof obj === "number") {
      return false;
    }
    return true; // 如果没有抛出异常，说明是有效的 JSON 字符串
  } catch (e) {
    return false; // 如果抛出异常，说明不是有效的 JSON 字符串
  }
}
export function errorHandler(err: any) {
  if (typeof err === "string") {
    // custom application error
    const is404 = err.toLowerCase().endsWith("not found");
    const status = is404 ? 404 : 400;
    return NextResponse.json(
      setJson({
        message: err,
        code: status,
      }),
      { status }
    );
  }

  if (err.name === "JsonWebTokenError") {
    // jwt error - delete cookie to auto logout
    return NextResponse.json(
      setJson({
        message: "Unauthorized",
        code: "401",
      }),
      { status: 401 }
    );
  }

  if (err.name === "UserExistsError") {
    return NextResponse.json(
      setJson({
        message: err.message,
        code: "422",
      }),
      { status: 422 }
    );
  }

  // default to 500 server error
  return NextResponse.json(
    setJson({
      message: err.message,
      code: "500",
    }),
    { status: 500 }
  );
}

export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs));
}

export function setCookie(cname: string, cvalue: string, exdays?: number) {
  let d = new Date();
  d.setTime(d.getTime() + (exdays = 24 * 60 * 60 * 1000));
  let expires = "expires=" + d.toDateString();
  document.cookie = cname + "=" + cvalue + "; " + expires;
}




